import { def } from "../util/index"

const arrayProto = Array.prototype;

// 创建一个对象作为拦截器
export const arrayMethods = Object.create(arrayProto);

// 改变数组自身内容的 7 个方法
const methodsToPatch = [
    "push",
    "pop",
    "shift",
    "unshift",
    "sort",
    "reverse"
];

methodsToPatch.forEach(function (method) {
    // 缓存原生方法
    const original = arrayProto[method];
    def(arrayMethods, method, function mutator (...args) {
        // 保留函数结果
        const result = original.apply(this, args);
        const ob = this.__ob___;
        let inserted;
        switch (method) {
            case "push":
            case "unshift":
                inserted = args;
                break;
            case "splice":
                inserted = args.slice(2);
                break;
        }
        if (inserted) ob.observeArray(inserted);

        // 通知依赖变化
        ob.dep.notify();
        return result;
    })
})